<?php

namespace App\Http\Controllers\Operation;

use App\Http\Controllers\Controller;
use App\Http\Requests\Operation\TemplateStyleRequest;
use App\Models\Operation\TemplateStyle;
use App\Repositories\Operation\TemplateStyleRepository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use Validator;

class TemplateStyleController extends Controller
{
    use ModelForm;

    /** @var  TemplateStyleRepository */
    private $templateStyleRepository;

    public function __construct(TemplateStyleRepository $templateStyleRepo)
    {
        $this->templateStyleRepository = $templateStyleRepo;
    }

    /**
     * Display a listing of the TemplateStyle.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('operation.template_styles.index_header'));
            $content->description(__('operation.template_styles.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new TemplateStyle.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('operation.template_styles.create_header'));
            $content->description(__('operation.template_styles.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created TemplateStyle in storage.
     *
     * @param TemplateStyleRequest $request
     *
     * @return Response
     */
    public function store(TemplateStyleRequest $request)
    {
        $input = $request->all();

        // 定义校验, 没有移到request
        $validator = Validator::make($request->all(), [
            'file' => 'required', // |mimes:xls,csv,xlsx
        ], [
            'required' => ':attribute 未上传',
            // 'mimes' => '文件格式只能为 :attribute',
        ], [
            'file' => '文件',
        ]);
        // 校验
        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'content' => '文件不能为空!']);
        }
        // 上传文件:
        $file = $request->file('file');
        // 获取客户端文件真实姓名
        // 文件是否上传成功
        if ($file->isValid()) {
            // 允许上传的文件格式
            $allowed_extensions = ["zip"];
            // 上传文件的后缀, 扩展名
            $entension = $file->getClientOriginalExtension();
            if ($entension && !in_array($entension, $allowed_extensions)) {
                // json返回
                return response()->json(['status' => 'error', 'content' => '文件格式只能为zip!']);
            }
            $realPath = $file->getRealPath();
            // 获取上传文件的名称
            $fileName = $file->getClientOriginalName();
            //获取文件尺寸
            $size          = $file->getSize();
            $input['size'] = $size;
            // 文件最大限制, 现在是10M
            $file_max_size = config('custom.base.file_max_size');
            // $size = round($file->getSize() / 1024 / 1024);
            if ($size > $file_max_size) {
                // json返回
                return response()->json(['status' => 'error', 'content' => '文件最大只能10M!']);
            }
            // 文件上传的根路径
            $rootDir = config('filesystems.disks.template.root');
            $path    = $file->move($rootDir . '/upload_template', $fileName);
            // 保存入模型时文件路径
            $fileUrl = '/upload_template/' . $fileName;

            /**
             * 文件上传成功之后对`.zip`文件进行操作
             */
            $zipper        = new \Chumper\Zipper\Zipper; //新建一个ZipArchive的对象
            $input['path'] = $fileUrl;

            $templateStyle = $this->templateStyleRepository->create($input);

            // 移动js,css及html,到相关的文件夹
            $moveJsPath     = config('custom.base.template_style.js.path');
            $moveCssPath    = config('custom.base.template_style.css.path');
            $moveImagesPath = config('custom.base.template_style.images.path');
            $moveWidgetPath = config('custom.base.template_style.widget.path');
            $moveViewPath   = config('custom.base.template_style.view.path');
            // zipper 负责将zip包中的文件解压到各个目录中去
            $zipper->make($rootDir . '/upload_template/' . $fileName)->folder('js')->extractTo($moveJsPath);
            $zipper->make($rootDir . '/upload_template/' . $fileName)->folder('css')->extractTo($moveCssPath);
            $zipper->make($rootDir . '/upload_template/' . $fileName)->folder('images')->extractTo($moveImagesPath);
            $zipper->make($rootDir . '/upload_template/' . $fileName)->folder('widget')->extractTo($moveWidgetPath);
            $zipper->make($rootDir . '/upload_template/' . $fileName)->folder('view')->extractTo($moveViewPath . $templateStyle->id);
            /**
             * 移动到相关位置后创建相关模板
             */
            // 获取压缩包下所有地文件
            $files = $zipper->make($rootDir . '/upload_template/' . $fileName)->listFiles('/\.php$/i');
            if (!empty($files)) {
                // 模板文件
                $templateBladeViews = [];
                foreach ($files as $fileValue) {
                    $tempArr = explode('/', $fileValue);
                    if ($tempArr[0] === 'view') {
                        $templateBladeViews[] = $tempArr[1];
                    }
                }
                // 如果模板文件不为空 , 则进行穿件模板
                if (!empty($templateBladeViews)) {
                    $contentTemplates = [];
                    foreach ($templateBladeViews as $key => $templateBladeView) {
                        $templateFileName                                   = explode('.', $templateBladeView);
                        $contentTemplates[$key]['template_style_id']        = $templateStyle->id;
                        $contentTemplates[$key]['template_no']              = $templateFileName[0];
                        $contentTemplates[$key]['name']                     = $templateFileName[0];
                        $contentTemplates[$key]['alias']                    = $templateFileName[0];
                        $contentTemplates[$key]['content_template_type_id'] = 1;
                        $contentTemplates[$key]['description']              = $templateFileName[0];
                        $contentTemplates[$key]['created_at']               = date('Y-m-d H:i:s', time());
                    }
                    // 向内容模板插入具体信息
                    // ContentTemplate::create($contentTemplates);
                    DB::table('content_templates')->insert($contentTemplates);
                }
            }
        } else {
            return response()->json(['status' => 'error', 'content' => '文件上传失败!']);
        }

        Flash::success(__('operation.template_styles.saved_success'));
        // 模板风格首页路由
        $url = route('operation.template_styles.index');
        return response()->json(['content' => '模板上传成功', 'status' => 'success', 'url' => $url]);

    }

    /**
     * Display the specified TemplateStyle.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $templateStyle = $this->templateStyleRepository->findWithoutFail($id);

        if (empty($templateStyle)) {
            Flash::error(__('operation.template_styles.not_found'));

            return redirect(route('operation.template_styles.index'));
        }

        return view('operation.template_styles.show')->with('templateStyle', $templateStyle);

    }

    /**
     * Show the form for editing the specified TemplateStyle.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('operation.template_styles.edit_header'));
            $content->description(__('operation.template_styles.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified TemplateStyle in storage.
     *
     * @param  int              $id
     * @param TemplateStyleRequest $request
     *
     * @return Response
     */
    public function update($id, TemplateStyleRequest $request)
    {
        $templateStyle = $this->templateStyleRepository->findWithoutFail($id);

        if (empty($templateStyle)) {
            Flash::error(__('operation.template_styles.not_found'));

            return redirect(route('operation.template_styles.index'));
        }
        $input = $request->all();

        $templateStyle = $this->templateStyleRepository->update($input, $id);

        Flash::success(__('operation.template_styles.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('operation.template_styles.index'));
    }

    /**
     * Remove the specified TemplateStyle from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->templateStyleRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('operation.template_styles.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $templateStyle = $this->templateStyleRepository->findWithoutFail($id);

        if (empty($templateStyle)) {
            Flash::error(__('operation.template_styles.not_found'));

            return redirect(route('operation.template_styles.index'));
        }

        if ($flag = $this->templateStyleRepository->delete($id)) {

            return response()->json(['message' => __('operation.template_styles.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(TemplateStyle::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '名称');
            $form->textarea('description', '描述');
            // $form->text('size', '文件大小');
            // $form->text('path', '存储路径');
            Admin::script('uploadTemplate();');

            $form->file('file', 'zip文件')->help('压缩文件后缀为.zip');

            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(TemplateStyle::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('operation.template_styles.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            // // 编辑按钮
            // if (!\Gate::check('operation.template_styles.edit')) {
            //     $actions->disableEdit();
            // }
            // // 删除按钮
            // if (!\Gate::check('operation.template_styles.destroy')) {
            //     $actions->disableDelete();
            // }
            // });

            // // 导出按钮
            // if (!\Gate::check('operation.template_styles.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('operation.template_styles.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('operation.template_styles.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 获取当前行模板的ID
                $id = $actions->row->id;
                // append 模板样式列表
                $actions->prepend('<a href="' . route('operation.content_templates.index',['template_style_id'=>$id]) . '" title="查看内容模板"><i class="fa fa-list"></i></a>');
                // 编辑按钮
                // if (Admin::user()->cannot('operation.template_styles.edit')) {
                $actions->disableEdit();
                // }
                // 删除按钮
                if (Admin::user()->cannot('operation.template_styles.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('operation.template_styles.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('operation.template_styles.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('description', '描述')->sortable();
            $grid->column('size', '文件大小')->sortable();
            $grid->column('path', '存储路径')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '模板风格名称');

            });
        });
    }
}
